import { _decorator, Component, Node, Prefab, Pool, director, instantiate } from 'cc';
import { Projectile } from './Projectile';
import { Events  } from '../events/Events';
const { ccclass, property } = _decorator;

@ccclass('ProjectileEmitter')
export class ProjectileEmitter extends Component {

    @property(Prefab)
    projectile:Prefab = null;

    private prefabPool: Pool<Node> = null;


    start() {
  
      const poolCount = 5;

      this.prefabPool = new Pool(() => {
          return instantiate(this.projectile!);
      }, poolCount, (node: Node) => {
          node.removeFromParent();
      });
    }

    onDestroy() {
      this.prefabPool.destroy();
    }

    create():Projectile {
      let node = this.prefabPool.alloc();
      if(!node.parent)
      {
        director.getScene()?.addChild(node);
      }
      node.active = true;
      node.once(Events.OnProjectileDead, this.onProjectileDead, this);
      let projectile = node.getComponent(Projectile);
      return projectile;
    }

    onProjectileDead(projectile:Projectile)
    {
      projectile.node.active = false;
      this.prefabPool.free(projectile.node);
    }


   
}

